package cn.heycm.blog.console.infra.dao.paramcfg;

import cn.heycm.blog.common.entity.page.Page;
import cn.heycm.blog.common.entity.result.CodeMsg;
import cn.heycm.blog.common.mybatis.PageUtil;
import cn.heycm.blog.common.utils.Assert;
import cn.heycm.blog.console.domain.paramcfg.ParamCfgRepository;
import cn.heycm.blog.console.infra.dao.paramcfg.entity.ParamCfg;
import cn.heycm.blog.console.infra.dao.paramcfg.mapper.ParamCfgMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

/**
 * @author hey
 * @version 1.0
 * @since 2024/9/18 22:13
 */
@Repository
@AllArgsConstructor
public class ParamCfgRepositoryImpl implements ParamCfgRepository {

    private final ParamCfgMapper mapper;

    @Override
    public void save(ParamCfg paramCfg) {
        ParamCfg cfg = mapper.selectByAlias(paramCfg.getParamAlias());
        if (null == cfg) {
            mapper.insertSelective(paramCfg);
            return;
        }
        Assert.isTrue(cfg.getParamId().equals(paramCfg.getParamId()), CodeMsg.CFG_EXISTS);
        mapper.updateByPrimaryKeySelective(paramCfg);
    }

    @Override
    public ParamCfg find(String paramAlias) {
        return mapper.selectByAlias(paramAlias);
    }

    @Override
    public Page<ParamCfg> page(int page, int size, String keyword) {
        PageInfo<ParamCfg> pageInfo = PageHelper.startPage(page, size)
                .doSelectPageInfo(() -> mapper.selectList(keyword));
        return PageUtil.convert(pageInfo);
    }
}
